// IDM 激活脚本管理器 - 主脚本
const SCRIPT_URL = 'https://raw.githubusercontent.com/lstprjct/IDM-Activation-Script/main/IAS.ps1';
const VERSION_CHECK_URL = 'https://api.github.com/repos/lstprjct/IDM-Activation-Script/commits/main';

let currentVersion = null;
let latestVersion = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    logMessage('系统', 'IDM 激活脚本管理器已启动');
    checkScriptVersion();
    
    // 绑定按钮事件
    document.getElementById('activateBtn').addEventListener('click', activateIDM);
});

// 检查脚本版本
async function checkScriptVersion() {
    try {
        updateStatusIndicator('checking', '检查更新中...');
        
        // 获取当前版本（通过HEAD请求的Last-Modified）
        const response = await fetch(SCRIPT_URL, { method: 'HEAD' });
        const lastModified = response.headers.get('Last-Modified');
        currentVersion = lastModified || new Date().toISOString();
        
        document.getElementById('currentVersion').textContent = formatDate(currentVersion);
        logMessage('系统', `当前脚本版本: ${formatDate(currentVersion)}`);
        
        // 检查最新版本
        const versionResponse = await fetch(VERSION_CHECK_URL);
        const versionData = await versionResponse.json();
        latestVersion = versionData.commit.author.date;
        
        // 比较版本
        if (new Date(latestVersion) > new Date(currentVersion)) {
            updateStatusIndicator('online', '有新版本可用');
            logMessage('系统', `发现新版本: ${formatDate(latestVersion)}`);
            showUpdateNotification();
        } else {
            updateStatusIndicator('online', '已是最新版本');
            logMessage('系统', '当前已是最新版本');
        }
        
        // 启用激活按钮
        document.getElementById('activateBtn').disabled = false;
        
    } catch (error) {
        logMessage('错误', `版本检查失败: ${error.message}`);
        updateStatusIndicator('offline', '版本检查失败');
        document.getElementById('activateBtn').disabled = false;
    }
}

// 激活IDM
async function activateIDM() {
    try {
        logMessage('系统', '开始下载 IDM 激活脚本...');
        
        // 下载脚本内容
        const response = await fetch(SCRIPT_URL);
        const scriptContent = await response.text();
        
        // 创建Blob并下载
        const blob = new Blob([scriptContent], { type: 'text/plain' });
        const url = window.URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = 'IDM-Activation-Script.ps1';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        
        window.URL.revokeObjectURL(url);
        
        logMessage('成功', '脚本已下载完成: IDM-Activation-Script.ps1');
        logMessage('提示', '请按以下步骤操作：');
        logMessage('步骤1', '1. 按 Win + X，选择"Windows PowerShell (管理员)"');
        logMessage('步骤2', '2. 输入: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser');
        logMessage('步骤3', '3. 输入: .\\IDM-Activation-Script.ps1');
        logMessage('步骤4', '4. 按照脚本提示完成激活');
        
        // 显示成功提示
        showSuccessAlert();
        
    } catch (error) {
        logMessage('错误', `下载失败: ${error.message}`);
        showErrorAlert(error.message);
    }
}

// 更新状态指示器
function updateStatusIndicator(status, text) {
    const indicator = document.getElementById('statusIndicator');
    const statusText = document.getElementById('updateStatus');
    
    indicator.className = `status-indicator status-${status}`;
    statusText.textContent = text;
}

// 记录日志
function logMessage(type, message) {
    const logArea = document.getElementById('logArea');
    const timestamp = new Date().toLocaleTimeString();
    const logEntry = `[${timestamp}] ${type}: ${message}\n`;
    
    logArea.textContent += logEntry;
    logArea.scrollTop = logArea.scrollHeight;
    
    // 保存到本地存储
    saveLog(logEntry);
}

// 清空日志
function clearLog() {
    document.getElementById('logArea').textContent = '[系统] 日志已清空\n';
    localStorage.removeItem('idmActivationLog');
}

// 刷新日志
function refreshLog() {
    loadLog();
    logMessage('系统', '日志已刷新');
}

// 保存日志到本地存储
function saveLog(entry) {
    let logs = localStorage.getItem('idmActivationLog') || '';
    logs += entry;
    localStorage.setItem('idmActivationLog', logs);
}

// 加载日志
function loadLog() {
    const logs = localStorage.getItem('idmActivationLog');
    if (logs) {
        document.getElementById('logArea').textContent = logs;
    }
}

// 显示更新通知
function showUpdateNotification() {
    const toast = document.createElement('div');
    toast.className = 'toast show position-fixed top-0 end-0 m-3';
    toast.setAttribute('role', 'alert');
    toast.innerHTML = `
        <div class="toast-header">
            <i class="fas fa-exclamation-triangle text-warning me-2"></i>
            <strong class="me-auto">更新提醒</strong>
            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
        </div>
        <div class="toast-body">
            检测到新版本脚本可用，建议更新后使用。
        </div>
    `;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, 5000);
}

// 显示成功提示
function showSuccessAlert() {
    const alert = document.createElement('div');
    alert.className = 'alert alert-success alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3';
    alert.setAttribute('role', 'alert');
    alert.style.zIndex = '9999';
    alert.innerHTML = `
        <i class="fas fa-check-circle me-2"></i>
        脚本下载成功！请按照日志中的步骤操作。
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alert);
    
    setTimeout(() => {
        if (alert.parentNode) {
            alert.parentNode.removeChild(alert);
        }
    }, 5000);
}

// 显示错误提示
function showErrorAlert(message) {
    const alert = document.createElement('div');
    alert.className = 'alert alert-danger alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3';
    alert.setAttribute('role', 'alert');
    alert.style.zIndex = '9999';
    alert.innerHTML = `
        <i class="fas fa-exclamation-triangle me-2"></i>
        下载失败: ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alert);
    
    setTimeout(() => {
        if (alert.parentNode) {
            alert.parentNode.removeChild(alert);
        }
    }, 5000);
}

// 格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN');
}

// 页面加载时加载日志
loadLog();